package com.eco.fanliapp.job.goodsfree;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.dao.AppUserMapper;
import com.eco.fanliapp.dao.SyDoubletwelveUserMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.DoubleElevenUserVo;
import com.eco.fanliapp.vo.DoubleTwelveUserVo;
import com.eco.fanliapp.vo.respone.DTKResponse;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 双十二活动奖励
 *
 * @date 2019-12-16
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DoubleTwelveTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(DTKGoodsFreeTask.class);

    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private SyDoubletwelveUserMapper syDoubletwelveUserMapper;
    @Autowired
    private RedisLockService redisLockService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private ISyUserMoneyLogService iSyUserMoneyLogService;

    public DoubleTwelveTask() {
    }

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行双十二活动奖励任务-DoubleTwelveTask：executeCount=" + executeCount + "--startTime=" + startTime);
        List<DoubleTwelveUserVo> listT = null;
        if (redisTemplateService.hasKey("app_doubleTwelve_winListT")) {
            listT = redisTemplateService.getTByListKey("app_doubleTwelve_winListT", DoubleTwelveUserVo.class);
        } else {
            listT = syDoubletwelveUserMapper.selectDoubletwelveUserList();
        }
        if (listT != null && listT.size() > 0) {
            for (DoubleTwelveUserVo vo : listT
            ) {
                AppUserOrder appUserOrder = iAppUserOrderService.findUserIdOrderId(vo.getUserId(), Long.valueOf(vo.getOrderId()));
                if (appUserOrder != null && appUserOrder.getOrderStatus() == 3 && appUserOrder.getOrderGrade() == 1) {
                    try {
                        for (DoubleTwelveUserVo deUserVo : listT
                        ) {
                            //redis锁-时间
                            long startTimes = System.currentTimeMillis() + 1000 * 3600 * 2400;

                            //获取锁
                            if (!redisLockService.lock("double_twelve_addUserMoney_" + deUserVo.getUserId(), startTimes + "")) {
                                log.info("双十二活动奖励，用户Id={}，时间={}", deUserVo.getUserId(), new Date());
                                continue;
                            }
                            if (deUserVo != null && deUserVo.getUserId() != null && deUserVo.getFreeMoney() != null) {
                                //通过用户id查询user ，加钱
                                AppUser appUser = iAppUserService.selectAppUserByUserId(deUserVo.getUserId());
                                if (appUser != null) {
                                    //用户不为空，加钱
                                    int ii = iAppUserService.updateAppUseraddbalance(deUserVo.getUserId(), BigDecimalUtils.Format(deUserVo.getFreeMoney()));
                                    log.info("双十二奖励 {}==用户id{}==金额{}", ii, deUserVo.getUserId(), deUserVo.getFreeMoney());
                                    if (ii > 0) {
                                        iAppNewsLogService.newsType(deUserVo.getUserId(),
                                                NewsEnumLog.NEWS_AWARDTWO_ACTIVITY.getNewsType(),
                                                BigDecimalUtils.Format(deUserVo.getFreeMoney()), deUserVo.getFreeMoney().toString());
                                        //增加log日志
                                        iSyUserMoneyLogService.addSyUserMoneyLog(deUserVo.getUserId(), appUser.getBalance(), BigDecimalUtils.Format(deUserVo.getFreeMoney()), "双十二活动免单奖励", 2, 0);
                                    //修改活动表记录已发放奖励状态
                                        syDoubletwelveUserMapper.updateStatusByUserId(deUserVo.getUserId());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                    }
                }
            }
            long endTime = System.currentTimeMillis();
            log.info("***************************************开始执行双十二活动奖励任务-DoubleTwelveTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

        }
    }
}
